Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

226
Views
Cannot read properties of undefined usding "This" in JavaScript class

I'm using Node JS and ExpressJS to write my web server. I use JavaScript OOP fromfew time. I get an error running this class:

class myClass  {

  constructor(path) {
    this.path = path;
  }


      
    myFunction(){

      var fileControllerInstance = new FileController(this.path);

      fileControllerInstance.fileExist(function(fileExist) {
        if(fileExist){
          console.log("file exist");
          this.printLine("test");
        }
        else
          return false;
      });
        
    }


    printSTR(str){
      console.log(str);
    }


    
}

new myClass("filePath").myFunction();
module.exports = myClass;

Running this class I get an error on printSTR function. Error is the follow:

file exist
TypeError: Cannot read properties of undefined (reading 'printSTR')

Without this I get ReferenceError: printSTR is not defined. To solve my problem I need to create another class instance and to use that to call the function. Something like this:

new myClass("filePath").printSTR("test") instead to ``` this.printLine("test"); ```

Why using this my code not working? Thanks

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Inside the function(fileExist), this has a different value than outside. To inherit the value inside, you must bind the function:

fileControllerInstance.fileExist(function(fileExist) {
  ...
}.bind(this));
over 4 years ago · Santiago Trujillo Report

0

You're calling this inside a callback. You can find this post useful to solve your issue.

Also you try to call printLine("test") but your method is printSTR(str)

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!